package com.yd.mvc.baseController;

import com.yd.app.util.BusinessException;
import com.yd.mvc.baseController.util.AuthUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


public class BaseController {


    protected String uploadFile(String url,HttpServletRequest request) throws Exception {
        // 上传文件存放路径
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        String fileurl="";
        String fieldName="";
        String dateStr=new Date().getTime()+"_";
        String file_dirs_url=url;//文件夹路径
        File makedirs=new File(file_dirs_url);
        if(!makedirs.exists()){
            makedirs.mkdirs();
        }
        File saveFile=null;
        try {
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    //获取路径名
                    String value = item.getName() ;
                    value=new String(value.getBytes("gbk"),"utf-8");
                    //索引到最后一个反斜杠
                    int start = value.lastIndexOf("\\");
                    //截取 上传文件的 字符串名字，加1是 去掉反斜杠
                    fieldName = value.substring(start+1);

                    fileurl=file_dirs_url+"/"+dateStr+fieldName;
                    saveFile = new File(fileurl);
                    item.write(saveFile); // 写入file，指向一个具体的文件
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return dateStr+fieldName;
    }
    protected String importFile(String url, HttpServletRequest request) throws Exception {
        // 上传文件存放路径
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        String fileurl="";
        String file_dirs_url=url;//文件夹路径
        File makedirs=new File(file_dirs_url);
        if(!makedirs.exists()){
            makedirs.mkdirs();
        }
        File saveFile=null;
        try {
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName="";
                if (!item.isFormField()) {
                    String value = item.getName() ;
                    fieldName = value;
                    fileurl=file_dirs_url+"/"+fieldName;
                    saveFile = new File(fileurl);
                    item.write(saveFile); // 写入file，指向一个具体的文件
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return fileurl;
    }
    protected void deleteFile(String url){
        File file = new File(url);
        if(file.exists() && !file.isDirectory()){
            file.delete();
        }
    }
    public  void downloadByUrl(HttpServletResponse response, String url, String fileName) throws Exception {
        InputStream fis = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(url));
        } catch (FileNotFoundException e) {
            throw new BusinessException(500,"该文件不存在");
        }
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
       // response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
        response.addHeader("Content-Length", "" + buffer.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }
    protected String getStringFromList(List<String> list){
        String returnStr="";
        if(list==null){
            return returnStr;
        }else{
            for(String str:list){
                returnStr+=str+",";
            }
        }
         return returnStr;
    }

    /**
     * 验证权限
     * @param permCode
     * @return
     */
    protected boolean getIfHasPerm(AuthUtil.AuthedUser user,String permCode) throws BusinessException {
        if(user.getPermCodeList().indexOf(permCode)==-1){
            throw new BusinessException(503,"尚未拥有该权限请联系管理员");
        }
        return true;
    }
}
